﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Text;
using CoffeeTeaTrading.Repository.Interfaces;

namespace CoffeeTeaTrading.Repository.Repositories
{
    public abstract class BaseRepository<T> : IRepository<T> where T : EntityObject, IDbEntity
    {
        readonly ObjectContext _context;
        readonly IObjectSet<T> _objectSet;

        protected BaseRepository(ObjectContext context)
        {
            _context = context;
            _objectSet = _context.CreateObjectSet<T>();
        }

        public IQueryable<T> GetAll()
        {
            return _objectSet.AsQueryable();
        }

        public void Delete(T item)
        {
            _objectSet.DeleteObject(item);
            _context.SaveChanges();
        }

        public void Save(T item)
        {
            if (item.ID <= 0)
            {
                //insert item
                _objectSet.AddObject(item);
                _context.SaveChanges();
            }
            else
            {
                //update item
                var oldItem = GetAll().Where(u => u.ID == item.ID).SingleOrDefault();
                if (oldItem == null)
                {
                    throw new ArgumentException("No such row found in DB");
                }
                UpdateItem(oldItem, item);
            }
            _context.SaveChanges();
        }

        protected abstract void UpdateItem(T oldItem, T item);
    }
}
